package de.hwrberlin.remo.diagram.properties;

import org.eclipse.emf.ecore.EObject;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.ui.views.properties.tabbed.TabbedPropertySheetPage;

import de.hwrberlin.remo.model.ElementState;
import de.hwrberlin.remo.model.LinkObject;


public class LinkStateSection extends AbstractRemoPropertySection {

	private Combo comboState;
	private Label labelState;
	
	@Override
	public void createControls(Composite parent,
			TabbedPropertySheetPage aTabbedPropertySheetPage) {
		super.createControls(parent, aTabbedPropertySheetPage);
		
		Composite sectionClient = getWidgetFactory().createFlatFormComposite(parent);
		sectionClient.setLayout(new FormLayout());
		
		labelState = getWidgetFactory().createLabel(sectionClient, "Invertiert:");

		FormData data = new FormData();
		data.top   = new FormAttachment(0, SectionConstants.TOP_MARGIN);
		data.left  = new FormAttachment(0, SectionConstants.LABEL_INDENT);
		data.width = SectionConstants.LABEL_WIDTH;
		labelState.setLayoutData(data);
		
		// ----------------------------------------------------------------------
		
		comboState  = new Combo(sectionClient, SWT.SINGLE | SWT.READ_ONLY | SWT.FLAT);
		comboState.addSelectionListener(stateSelectionListener);

		data = new FormData();
		data.top   = new FormAttachment(0, SectionConstants.TOP_MARGIN);
		data.left  = new FormAttachment(labelState);
		data.right = new FormAttachment(55);
		comboState.setLayoutData(data);
		
		for(ElementState s : ElementState.values()) {
			if (s.getName() != "UNKNOWN" ) {
				comboState.add(s.getName());
			}
		}
	}
	
	@Override
	public void refresh() {
		EObject eObject = getEObject();
	
		if(eObject != null && eObject instanceof LinkObject) {
			LinkObject exElement = (LinkObject) eObject;
			
			int value= exElement.getLinkstate().getValue();
			comboState.select(value);
		} 
	}
	
	//////////////
	/* Listener */
	
	private SelectionListener stateSelectionListener = new SelectionAdapter() {
		@Override
		public void widgetSelected(SelectionEvent e) {
			eObject = getEObject();
			
			if(eObject != null && eObject instanceof LinkObject) {
				ElementState newState = ElementState.get(comboState.getSelectionIndex());
				editingHelper.setElementState((LinkObject) eObject, newState);
			}
		}	
	};
}